using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Entity;
using System.Data.SqlClient;
using Menfram.DAL.Abstract;
using Menfram.Entity.Interface;

namespace DAO
{
    public class ColunasDAO : AbstractDAO<ColumnEntity>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public IEntity retornaEntidade(System.Data.SqlClient.SqlDataReader reader)
        {
            Entity.ColumnEntity tb = new Entity.ColumnEntity();
            tb.NomeColuna = reader["column_name"].ToString();
            tb.TipoColuna = reader["data_type"].ToString();
            tb.Tamanho = Convert.ToInt32(reader["length"].ToString());
            int isnull = Convert.ToInt32(reader["isnullable"].ToString());
            if (isnull == 0)
            {
                tb.IsNullable = true;
            }
            else {
                tb.IsNullable = false;
            }
            if (tb.NomeColuna.Length > 4 && tb.NomeColuna.Remove(0, 4) == "SEQUENCIAL")
            {
                tb.IsChave = true;
            }
            return tb;
        }
       
        public IList<ColumnEntity> findAllColunasByTableName(String tableName)
        {
            IList<ColumnEntity> lista = new List<ColumnEntity>();
            try
            {
                string sql =
                "select 	object_name(c.id) as table_name, c.name as column_name, t.name as data_type, c.length, c.isnullable, c.colorder " +
                "  from	syscolumns c inner join systypes t " +
                " on	c.xtype	= t.xtype " +
                " where	c.id	= object_id('" + tableName + "') order by c.colorder";
                SqlDataReader reader = (SqlDataReader)executeQuery(sql);
                while (reader.Read())
                {
                    lista.Add((ColumnEntity)retornaEntidade(reader));
                }
                reader.Close();
            }
            catch
            {
            }

            return lista;
        }

        private ColunasDAO() { }
        private static ColunasDAO dao = null;
        public static ColunasDAO getInstance()
        {
            if (dao == null) {
                dao = new ColunasDAO();
            }
            return dao;
        }

        public override Type getTipo()
        {
            return typeof(ColumnEntity);
        }
    }
}
